/**
 * Created by admin on 2017/9/13.
 */
define([
    "helpers/network",
    "views/modules/popup",
    "views/modules/pager",
    "views/modules/form",
    "views/modules/popup",
    "models/system"
], function (Network, Popup, CommonPager, CommonForm, PopupView, System) {

    var id = "";
    var tableId = id + "table";
    var TYPE = "SystemConfig";
    var pagerId = id + "pager";
    var totalCountsId = id + "totalCounts";
    var keywordsId = id + "keyWord";
    var searchFormId = id + "searchForm";
    var windowsId = id + "window";
    var formId = id + "form";
    var rejectWindowId = id + "rejectWindowId";
    var pageIndex = 1;

    var onTableReady = function (page) {
        var searchForm = $$(searchFormId).getValues();
        var obj = {
            params: {
                keyWord: searchForm[keywordsId] ? searchForm[keywordsId] : undefined,
                bizs: ["System", "External"]
            },
            size :20,
            page: page,
            sort: ["id,asc"]
        };
        Network.ajax("/SystemConfigurationView.queryAll.query", obj, function (ret) {
            $$(tableId).clearAll();
            $$(tableId).parse(ret.data.content);
            CommonPager.refreshPager(page, ret.data.totalPages);
            $$(totalCountsId).setValue(ret.data.totalElements + "条数据, 共" + ret.data.totalPages + "页");
        })
        pageIndex = page ? page : 1
    };

    var genSearchFormUI = function () {
        return {
            view: "scrollview", scroll: "x",
            body: {
                id: searchFormId, view: "form", css: "toolbar", paddingY: 5, paddingX: 10,
                cols: [
                    {},
                    // {
                    //     id: "static", name: "static", view: "select", width: 80, css: {"text-align": "center"},
                    //     value: "mobile",
                    //     options: ModelAdmin.adminSearchTypes
                    // },
                    CommonForm.genKeywordsUI(keywordsId, "根据参数标示进行检索", onTableReady),
                    // CommonForm.genMultiOptionsSelector(accountStatusId, "账号状态", ModelAdmin.accountStatus),
                    CommonForm.genQueryButtonUI(onTableReady)
                ]
            }
        }
    };

    var updateSystem = function (item) {
        console.log(item)
        var type = item.type
        if (type == "list") {
            item["value"] = item.listValue
        } else if (type == "json") {
            item["value"] = item.jsonValue
        } else if (type == "text") {
            item["value"] = item.textValue
        }
        var obj = {
            data: {
                id: item.id,
                value: item.value
            }
        }
        Network.ajax("/SystemConfigurationTransactor.update.command", obj, function (ret) {
            closeWindow();
            webix.message("操作成功！")
            onTableReady(1);

        })
    }

    var optionsData = function (item) {
        var data = []
        var items = item.definition.items;
        for (var o=0; o < items.length ; o++){
            data.push({id:items[o].value, value:items[o].text})
        }
        return data
    }

    var showWindow = function (title, item) {
        console.log(item)
        item = item || {data: {}};
        var type = item.definition.type
        PopupView(windowsId, title, {
            rows: [
                {
                    cols: [
                        {
                            view: "scrollview", scroll: "y", gravity: 0.4, padding: 0,
                            body: {
                                // rows: [
                                //             {
                                view: "form", borderless: true, id: formId,
                                elements: [
                                    {
                                        id: "id", name: "id", view: "text", hidden: true,
                                        value: item.id || ""
                                    },
                                    {
                                        id: "type", name: "type", view: "text", hidden: true,
                                        value: type || ""
                                    },
                                    {
                                        id: "vParamText", view: "text", name: "vParamText", readonly: true, required: true,
                                        label: "参数值",
                                        value: item.vParamText || ""
                                    },
                                    {
                                        id: "listValue", name: "listValue", view: "select", label: "内容", fillspace: true, required: true,
                                        options: type == "list" ? optionsData(item) :System.listData  , hidden: type == "list" ? false : true,
                                        value: item.value || "",
                                    },
                                    {
                                        id: "jsonValue", view: "textarea", name: "jsonValue", height: 400, fillspace: true, required: true,
                                        label: "内容", hidden: type == "json" ? false : true,
                                        value: item.value || "",
                                    },
                                    {
                                        id: "valueS", view: "text", name: "textValue", required: true,
                                        label: "内容", hidden: type == "text" ? false : true,
                                        value: item.value || "",
                                    },
                                ]
                            }
                        }
                    ]
                },
                {
                    padding: 5,
                    cols: [{}, {
                        view: "button", label: "确定", width: 90,
                        click: function () {
                            if (!$$(formId).validate()) {
                                webix.message("信息填写有误, 请仔细录入...");
                                return
                            }
                            var itemValues = $$(formId).getValues();
                            updateSystem(itemValues);
                        }
                    },
                    ]
                }
            ]
        }, 500, 400, function () {
            onWindowReady(item)
        }, closeWindow);
    };

    var closeWindow = function () {
        if ($$(windowsId)) {
            $$(windowsId).close();
        }
        if ($$(rejectWindowId)) {
            $$(rejectWindowId).close();
        }
    };

    var onWindowReady = function (item) {
        if (item.definition.type == "json") {
            try {
                console.log("进入错误捕获")
                var value = JSON.stringify(JSON.parse(item.value), undefined, 4);
                $$("jsonValue").setValue("");
                $$("jsonValue").setValue(value);
            } catch (ex) {
                var err = "错误描述:" + ex
                webix.message({type: "error", text: "书写了错误的JSON格式，请仔细检查，以避免发生不可想象的事情!!" + err})
                $$("jsonValue").setValue("");
                $$("jsonValue").setValue(item.value);
            }
        }
    };

    var genOperationFormUI = function () {
        return {
            view: "scrollview", scroll: "x",
            body: {
                view: "form", css: "toolbar", paddingY: 5, paddingX: 10,
                cols: [
                    {view: "label", label: "操作"},
                    {
                        view: "button", label: "修改", width: 90,
                        // hidden: Authority.hasNoAuth("GOODS_MODIFY"),
                        click: function () {
                            if ($$("table").getSelectedItem()) {
                                showWindow("设置", $$("table").getSelectedItem())
                            }
                        }
                    }
                ]
            }
        }
    };

    var returnData = function (obj) {
        var value = obj.value;
        var definition = obj.definition;
        var items =definition.items
        if (definition.type == "list") {
            for (var o=0; o < items.length; o++){
                if(value == items[o].value){
                    return items[o].text
                }
            }
        } else {
            return obj.value
        }
    }

    var genDataTableUI = function () {
        return {
            id: tableId, view: "datatable", resizeColumn: true, select: "row", data: [], complexData: true,
            ready: onTableReady,
            on: {
                onItemClick: function (id) {
                }
            },
            columns: [
                {
                    id: "id", header: "ID", fillspace: true,
                },
                {
                    id: "param", header: "参数名字", fillspace: true,
                },
                {
                    id: "vParamText", header: "参数标示", fillspace: true,
                    // template: function (obj) {
                    //     return obj.definition ? obj.definition.type : ""
                    // }
                },
                {
                    id: "definition", header: "参数说明", fillspace: true,
                    template: function (obj) {
                        return obj.definition ? obj.definition.type : ""
                    }
                },
                {
                    id: "value", header: "值", fillspace: true,
                    template: function (obj) {
                       return returnData(obj,function () {})
                    }
                }
            ]
        }
    }

    var genFooterUI = function () {
        return {
            cols: [
                CommonPager.genPagerUI(pagerId, onTableReady),
                CommonPager.genTotalCountsUI(totalCountsId), {}
            ]
        }
    };

    var layout = {
        // type: "clean",
        padding: 10,
        rows: [
            genSearchFormUI(),
            genOperationFormUI(),
            genDataTableUI(),
            genFooterUI(),
        ]
    };

    return {$ui: layout};

});